<?php

namespace common\observer;

use common\model\TaskModel;
use common\service\StepService;
use support\SingletonTrait;
use common\service\CommonService;
use common\service\StatusService;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 任务状态变化 自动保存开始时间和结束时间
 */
class StartEndTimeAutoSave implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     */
    function update(SplSubject $subject): void
    {
        $updateData = $subject->getSplUpdateData();
        if (!isset($updateData['task_status'])) {
            return;
        }
        $task = $subject->getSubjectData();

        try {
            if ($updateData['task_status'] == StatusService::getInstance()->getTaskDefaultStartStatus()['id']
                && $task['start_time'] == 0
            ) {
                $data = [
                    'id' => $subject->getSplPrimaryId(),
                    'start_time' => time(),
                ];
                CommonService::instance('task')->update($data, 'task', false);
            }

            if ($updateData['task_status'] == StatusService::getInstance()->getTaskDoneStatus()['id']) {
                $step = StepService::getInstance()->getStep($task['step_id']);
                // 子任务在变成完成的时候 自动修改为
                if (in_array($task['step_type'], TaskModel::STEP_TYPE_TODO_GROUP) || !empty($step) && $step['is_dismantle_step'] == 'yes') {
                    $data = [
                        'id' => $subject->getSplPrimaryId(),
                        'end_time' => time(),
                        'delivery_time' => time(),
                    ];
                    CommonService::instance('task')->update($data, 'task', false);
                }
            }

        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
